package com.qingyu.print.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qingyu.common.utils.PageUtils;
import com.qingyu.common.utils.Query;

import com.qingyu.print.order.dao.OrderDao;
import com.qingyu.print.order.entity.OrderEntity;
import com.qingyu.print.order.service.OrderService;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Resource
    private OrderDao orderMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<OrderEntity> getByPhone(String phone) {
        String orderJson = redisTemplate.opsForValue().get(phone);
        System.out.println(orderJson);
        if(!StringUtils.hasLength(orderJson)) {
            QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
            wrapper.in("uid", phone);
//        OrderEntity orderEntity = orderMapper.selectOne(wrapper);
            List<OrderEntity> orderEntities = orderMapper.selectList(wrapper);
            System.out.println(orderEntities);
            String s = JSON.toJSONString(orderEntities);
            redisTemplate.opsForValue().set(phone,s,5, TimeUnit.MINUTES);
            return orderEntities;
        }
        List<OrderEntity> orderEntities = JSON.parseObject(orderJson, new TypeReference<List<OrderEntity>>(){});

        return orderEntities;
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        OrderEntity entity = this.getById(orderEntity.getId());
        if (entity.getStatus()==0){
            entity.setStatus(4);
            this.updateById(entity);
            System.out.println("已取消订单");
        }
    }


}